package com.redis.springbootredis.service.impl;

import com.redis.springbootredis.dao.CourseDao;
import com.redis.springbootredis.entity.Course;
import com.redis.springbootredis.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @create 2020-10-30 12:02
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    CourseDao courseDao;

    @Override
    public Course getCourseByCid(Integer cid) {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Course course = null;
        if(!redisTemplate.hasKey("course"+cid)){
            System.out.println("查询数据库");
            course = courseDao.selectCourseByCid(cid);
            //将查询的数据存进缓存
            opsForValue.set("course"+cid,course);
        }else{
            System.out.println("缓存");
            course = (Course) opsForValue.get("course"+cid);
        }
        return course;
    }

    //带分页查询
    @Override
    public List<Course> getCourseByLimit(Integer pageIndex,Integer pageSize) {
        List<Course> courses = null;
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        if(!redisTemplate.hasKey("courseByLimit")){
            System.out.println("查询数据库");
            courses = courseDao.selectCourseByLimit(pageIndex, pageSize);
            opsForValue.set("courseByLimit",courses);
        }else{
            System.out.println("缓存");
            courses = (List<Course>) opsForValue.get("courseByLimit");
        }
        return courses;
    }

    @Override
    public void addCourse(Course course) {
        courseDao.insertCourse(course);
    }

    @Override
    public void removeCourse(Integer cid) {
        courseDao.deleteCourse(cid);
    }

    @Override
    public void updateCourse(Integer cid,String cname) {
        courseDao.modifyCourse(cid,cname);
    }
}
